package com.itheima.es.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.es.springboot.mapper.UserMapper;
import com.itheima.es.springboot.pojo.TbSku;
import com.itheima.es.springboot.service.UserService;
import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 雪落
 * @date 2020/12/30 - 0:01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TbSku> implements UserService {
    //客户端对象
    private RestHighLevelClient client;
    @Autowired
    UserMapper userMapper;

    {
        //创建Rest客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        //如果是集群，则设置多个主机，注意端口是http协议的端口
                        new HttpHost("192.168.200.150", 9200, "http")
//                        ,new HttpHost("localhost", 9201, "http")
//                        ,new HttpHost("localhost", 9202, "http")
                )
        );
    }


    public void SqlConversionElasticSearch() throws IOException {

        // 1.从数据库查询文档数据
        //第一步：准备数据源。本案例使用List来模拟数据源。
        List<TbSku> users = userMapper.listes();
        System.out.println(users!=null);
        // 2.创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();
        // 3.创建多个IndexRequest对象，并添加到BulkRequest中
        for (TbSku user : users) {
            bulkRequest.add(new IndexRequest("userppp")
                    .id(user.getId().toString())
                    .source(JSON.toJSONString(user), XContentType.JSON)
            );
        }
        // 4.发起请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println("status: " + bulkResponse.status());
        client.close();
    }

    public void ElasticSearchstart() throws IOException {
        // System.out.println(client);
        // org.elasticsearch.client.RestHighLevelClient@6c61a903
        // 1.创建CreateIndexRequest对象，并指定索引库名称
        CreateIndexRequest request = new CreateIndexRequest("userppp");
        // 2.指定settings配置(可以默认)
        System.out.println("开始干活");
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)     //number_of_shards   是数据分片数，默认为5，有时候设置为3
                .put("index.number_of_replicas", 1)   //number_of_replicas 是数据备份数，如果只有一台机器，设置为0
        );
        // 3.指定mapping配置
        request.mapping("{\n" +
                        "        \"properties\" : {\n" +
                        "        \"id\" : {\n" +
                        "          \"type\" : \"keyword\"\n" +
                        "        },\n" +
                        "        \"name\" : {\n" +
                        "          \"type\" : \"text\",\n" +
                        "          \"analyzer\" : \"ik_max_word\"\n" +
                        "        },\n" +
                        "        \"price\" : {\n" +
                        "          \"type\" : \"integer\"\n" +
                        "        },\n" +
                        "        \"num\" : {\n" +
                        "          \"type\" : \"integer\"\n" +
                        "        },\n" +
                        "        \"image\" : {\n" +
                        "          \"type\" : \"keyword\"\n" +
                        "        },\n" +
                        "        \"create_time\" : {\n" +
                        "          \"type\" : \"date\"\n" +
                        "        },\n" +
                        "        \"category_id\" : {\n" +
                        "          \"type\" : \"integer\"\n" +
                        "        },\n" +
                        "        \"category_name\" : {\n" +
                        "          \"type\" : \"text\",\n" +
                        "          \"analyzer\" : \"ik_max_word\"\n" +
                        "        },\n" +
                        "        \"brand_name\" : {\n" +
                        "          \"type\" : \"text\",\n" +
                        "          \"analyzer\" : \"ik_max_word\"\n" +
                        "        }\n" +
                        "      }\n" +
                        "      }",
                //指定映射的内容的类型为json
                XContentType.JSON);
        // 4.发起请求，得到响应（同步操作）
        System.out.println(client);
        CreateIndexResponse response = client.indices()
                    .create(request, RequestOptions.DEFAULT);


        //打印结果
        System.out.println("response = " + response.isAcknowledged());
        client.close();
    }
}
